// 确认退出用户。
function confirmLogout() {
    if (confirm("Are you sure you want to log out?")) {
        window.location.href = concatWithBaseURL("/logout");
    }
}



/* 动态设置链接样式 */
document.addEventListener('DOMContentLoaded', function () {
    const currentPath = window.location.pathname;
    const links = document.querySelectorAll('.edit-link');
    links.forEach(link => {
        if (currentPath.endsWith(link.getAttribute('href'))) {
            link.classList.add('active-link');
        } else {
            link.classList.add('inactive-link');
        }
    });
});

function urlJoin(url1, url2) {
    return url1.replace(/\/$/, '') + '/' + url2.replace(/^\//, '');
}

function concatWithBaseURL(reqTargetURL) {
    // 获取base url
    // reqTargetURL: 当前页面没有被nginx代理时候的url，那么就应该直接请求
    // const reqTargetURL = "{{ url_for('login') }}";
    // 当前页面的url
    // const currentPathName = window.location.pathname;
    // // 从当前页面url寻找到reqTarget的位置
    // if (currentPathName.endsWith(reqTargetURL)) {
    //     const baseURL = currentPathName.substring(0, currentPathName.length - reqTargetURL.length);

    //     return urlJoin(baseURL, reqTargetURL);
    // } else {
    //     console.error("current pathname is not ended with reqTargetURL", currentPathName, reqTargetURL)
    //     return reqTargetURL;
    // }
    const base = document.querySelector("base")

    baseURL = base ? base.getAttribute("href") : "";
    return urlJoin(baseURL, reqTargetURL);
}


// 修改所有表单 action，加上 base path
document.addEventListener("DOMContentLoaded", function () {
    const forms = document.querySelectorAll("form");
    forms.forEach(form => {
        let action = form.getAttribute("action");

        if (action && !action.startsWith("http")) {
            // 如果没有 base path 前缀，则添加
            // if (action.startsWith("/")) {
            form.setAttribute("action", concatWithBaseURL(action));
            // }
        }
    });
});

// 封装 fetch
function apiFetch(relativeUrl, options = {}) {
    return fetch(concatWithBaseURL(relativeUrl), options);
}
// 封装  ajax请求，注意必须导入ajax。
function ajaxRequest(options) {
    options.url = concatWithBaseURL(options.url);
    return $.ajax(options);
}
function ajaxGet(relativeUrl, success) {
    return $.get(concatWithBaseURL(relativeUrl), success)
}

window.apiFetch = apiFetch;
window.ajaxRequest = ajaxRequest;
window.ajaxGet = ajaxGet;